import { NavigationActions} from 'react-navigation';
var nav;

const initNavigation = (navigation) => {
  nav = navigation;
}

const navigation = (navgation,data) =>{
  const {navigate} = nav;
  navigate(navgation,data);
}

const reset = (routeName) => {
  const resetAction = NavigationActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({ routeName })]
  });
  nav.dispatch(resetAction);
};

const back = (navgation) =>{
  const {goBack} = navgation;
  goBack();
}

const target = (url,data) =>{
  const {navigate} = nav;
  if(url.startsWith("http://") || url.startsWith("https://")){
    navigate("Web",{url,...data});
  }else if(url.startsWith("app://")){
    try{
      let us = url.split("?");
      let params = {};
      if(us.length>1){
        let ps = us[1];
        let pss = ps.split("&");
        pss.map(r=>{
          let eq = r.split("=");
          params[eq[0]]=eq[1];
        })
      }
      if(data){
        navigate(us[0].replace("app://",""),{...params,...data});
      }else{
        navigate(us[0].replace("app://",""),{...params});
      }
    }catch(e){

    }
  }else{
    navigate(url,data);
  }
}

const pop = (count, immediate) => {
  nav.dispatch(NavigationActions.pop({
    n: count,
    immediate: immediate,
  }));
}

export default {
  reset,
  back,
  navigation,
  initNavigation,
  target,
  pop
};
